<template>
    <div class="form">
        <div class="input">
            <div class="title">
                注册
            </div>
            <div class="mb20"/>
            <el-form
                ref="input"
                label-position="left"
                label-width="80px"
                :model="signInForm">
                <el-form-item
                    prop="email"
                    label="邮箱"
                    :rules="[
                        {
                            required: true,
                            message: '请输入邮件地址',
                            trigger: 'blur'
                        },
                        {
                            type: 'email',
                            message: '请输入正确的邮件地址',
                            trigger: ['blur', 'change']
                        },
                    ]">
                    <el-input v-model="signInForm.email"/>
                </el-form-item>
                <el-form-item
                    prop="pwd"
                    label="密码"
                    :rules="[
                        {
                            required: true,
                            message: '请输入密码',
                            trigger: 'blur'
                        },
                        {
                            validator: validatePwdLen,
                            trigger: ['blur']
                        }
                    ]">
                    <el-input v-model="signInForm.pwd" show-password/>
                </el-form-item>
                <el-form-item
                    prop="check_pwd"
                    label="确认密码"
                    :rules="[
                        {
                            required: true,
                            message: '请再次输入密码',
                            trigger: 'blur'
                        },
                        {
                            validator: validateChkPwd,
                            trigger: ['blur', 'change']
                        }
                    ]">
                    <el-input v-model="signInForm.check_pwd" show-password/>
                </el-form-item>
                <el-form-item
                    prop="key"
                    label="验证码"
                    :rules="[
                        {
                            required: true,
                            message: '请输入验证码',
                            trigger: 'blur'
                        }
                    ]">
                    <el-input v-model="signInForm.key">
                        <template #append>
                            <el-button v-if="keyInterval == 0" @click="getKey()">获取验证码</el-button>
                            <el-button v-else>{{keyInterval}}秒后可重新获取</el-button>
                        </template>
                    </el-input>
                </el-form-item>
            </el-form>
            <div class="tip">
                <label>
                    已有账号？点击
                    <span @click="toLogin()">登录</span>
                </label>
            </div>
            <div class="action">
                <span @click="register()">注册</span>
            </div>
        </div>
    </div>
</template>

<script>
import axios from "@/utils/MyAxios"
import qs from "qs"
import { ElMessage } from "element-plus"
export default {
    name: 'LoginForm',
    data() {
        var validateChkPwd = (rule, value, callback) => {
            if (value !== this.signInForm.pwd)
                callback(new Error('两次输入密码不一致!'))
            else
                callback()
        }
        var validatePwdLen = (rule, value, callback) => {
            if (value.length > 20 || value.length < 6)
                callback(new Error('密码长度应在6~20位'))
            else
                callback()
        }
        return {
            signInForm: {
                email: '',
                pwd: '',
                check_pwd: '',
                key: ''
            },
            keyInterval: 0,
            timer: null,
            validatePwdLen,
            validateChkPwd,
            reg: /^[a-zA-Z0-9_.-]+@[a-zA-Z0-9-]+(\.[a-zA-Z0-9-]+)*\.[a-zA-Z0-9]{2,6}$/
        }
    },
    methods: {
        register() {
            this.$refs.input.validate((valid) => {
                if (valid) {
                    let data = {
                        email: this.signInForm.email,
                        code: this.signInForm.key
                    }
                    axios.post('/api/user/checkCode', qs.stringify(data))
                        .then((response) => {
                            console.log(response)
                            if (response.data.code == 0) {
                                data = {
                                    email: this.signInForm.email,
                                    password: this.signInForm.pwd
                                }
                                axios.post('/api/user/register', qs.stringify(data))
                                    .then(res => {
                                        console.log(res)
                                        data = res.data
                                        if (data.code == 0) {
                                            ElMessage.success({message: data.msg, showClose: true})
                                            let user = {
                                                token: data.data.token
                                            }
                                            localStorage.setItem('user', JSON.stringify(user))
                                            localStorage.setItem('token', user.token)
                                            window.open('/index', '_self')
                                        } else {
                                            ElMessage.error({message: data.msg, showClose: true})
                                        }
                                    })
                                    .catch(err => {
                                        console.log(err)
                                        ElMessage.info({message: err.message, showClose: true})
                                    })
                            } else {
                                ElMessage.error({message: response.data.msg, showClose: true})
                            }
                        })
                        .catch(error => {
                            ElMessage.info({message: error.message, showClose: true})
                        })
                }
            })
        },
        toLogin() {
            this.$router.replace('/user/sign/login')
        },
        getKey() {
            console.log(1)
            if (!this.signInForm.email) {
                ElMessage.error({
                    message: '请先输入邮箱',
                    showClose: true
                })
            } else if (this.reg.test(this.signInForm.email)) {
                axios.post('/api/user/check', qs.stringify({email: this.signInForm.email}))
                    .then(res => {
                        // ElMessage({message: res.data.msg, showClose: true})
                        if (res.data.code == 0) {
                            this.keyInterval = 30
                            var timer = setInterval(()=>{
                                this.keyInterval -= 1
                                if (this.keyInterval == 0) {
                                    clearInterval(timer)
                                    timer = null
                                }
                            }, 1000)
                            axios.post('/api/user/sendCode', qs.stringify({email: this.signInForm.email}))
                                .then(response=>{
                                    console.log(response)
                                    ElMessage({
                                        message: response.data.msg,
                                        showClose: true
                                    })
                                })
                                .catch(err=>{
                                    console.log(err)
                                    ElMessage({message: err.message, showClose: true})
                                })
                        } else {
                            ElMessage({message: res.data.msg, showClose: true})
                        }
                    })
            } else {
                ElMessage.error({
                    message: '邮箱格式错误',
                    showClose: true
                })
            }
        }
    }
}
</script>

<style scoped>
.form {
    width: 100%;
    height: auto;
    display: flex;
    flex-direction: column;
    justify-content: center;
    align-items: center;
}
.title {
    margin: 10px;
    text-align: left;
    font-size: 30px;
}
.mb20 {
    margin-bottom: 20px;
}
.tip {
    display: flex;
    flex-direction: row-reverse;
}
.tip > label {
    font-size: 10px;
}
.tip > label > span {
    color: #4ab3fa;
    cursor: pointer;
}
.action {
    display: inline-flex;
    width: 80%;
    height: 40px;
    margin: 10px;
}
.action span {
    width: 100%;
    background-color:#0076CC;
    color: #fff;
    margin-inline: 15px;
    cursor: pointer;
    font-size: 20px;
    line-height: 40px;
    border-radius: 10px;
}
</style>